<template>
  <Spin :spinning="loading" tip="Loading...">
  <div>
    <!-- 索赔结算单查询-详情页面 -->
    <BreakSpace label="结算单信息" :containerStyle="{ marginBottom: '10px' }" />
    <FormPanel ref="formPanel" :list="formList" :cols="3" :formType="'add'" labelWidth="110" :isSubmitBtn="false" @formChange="formChangeHandle" />
    <BreakSpace label="索赔单列表" :containerStyle="{ marginBottom: '10px' }" />
    <FilterTable
      ref="table"
      :columns="columns"
      :params="fetchParams"
      :datakey="'items'"
      :onColumnsChange="(columns) => (this.columns = columns)"
      :onRowSelectChange="selectChange"
      :isPagination="false"
      :isSelectColumn="false"
      height="auto"
      :is-select-column="false"
    >
      <template slot="controls" slot-scope="props">
        <multiuse-button size="small" type="primary" icon="el-icon-plus" @click="suopeidanadd()">添加</multiuse-button>
      </template>
    </FilterTable>
    <BaseDialog :visible.sync="suopeidanFlag" :title="'索赔单选择'" width="850px" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <Selectsuopeidan @close="suopeidanclose" @save="suopeidansave" :rowData="carType"></Selectsuopeidan>
    </BaseDialog>
    <BreakSpace label="考核单列表" :containerStyle="{ marginBottom: '10px' }" />
    <FilterTable
      ref="table1"
      :columns="columns1"
      :params="fetchParams"
      :datakey="'items'"
      :onColumnsChange="(columns1) => (this.columns1 = columns1)"
      :onRowSelectChange="selectChange"
      :isPagination="false"
      :isSelectColumn="false"
      height="auto"
      :is-select-column="false"
    >
      <template slot="controls" slot-scope="props">
        <multiuse-button size="small" type="primary" icon="el-icon-plus" @click="kaohedanadd()">添加</multiuse-button>
      </template>
    </FilterTable>
    <div style="margin-bottom: 1rem"></div>
    <BaseDialog :visible.sync="kaohedanFlag" :title="'考核单选择'" width="850px" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <SelectKaoHedan @close="kaohedanclose" @save="kaohedansave" :rowData="carType"></SelectKaoHedan>
    </BaseDialog>
    <div style="padding-top: 3rem"></div>
    <div
      :style="{
        position: 'fixed',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right',
      }"
    >
      <multiuse-button type="primary" :click="saveDialog.bind()">保 存</multiuse-button>
      <multiuse-button @click="closeDialog">关 闭</multiuse-button>
    </div>
  </div>
  </Spin>
</template>
<script>
import Selectsuopeidan from './Selectsuopeidan.vue';
import SelectKaoHedan from './SelectKaoHedan.vue';
import { isFormEmpty } from '@/utils/index';
import { getListByPage, getPartType, getclaimType, deleteOne, editSave, quyrPSettle } from '@/api/claim/dealer/ClaimStatementMaintain';
import {  getAppId } from '@/assets/js/auth';
import { dictionary } from '@/utils/dictMixin';
export default {
  mixins: [dictionary],
  props: ['rowData'],
  components: {
    Selectsuopeidan,
    SelectKaoHedan,
  },
  data() {
    return {
      loading: false,
      dataList: [],
      dataList1: [],
      kaohesum: 0,
      suopeisum: 0,
      huanxiajiandataList: [],
      fujiaxiangmudataList: [],
      visible: false,
      //索赔单列表开关
      suopeidanFlag: false,
      kaohedanFlag: false,
      visibleDrawer: false,
      collapse: false,
      infoId: null,
      flterValue: {}, //参数
      columns: this.creatHeader(),
      columns1: this.creatHeader1(),
      fetchParams: {}, //ipa 接口
      selectedRows: [], //选中经销商
      formList: this.createFormList(),
      editRow: {},
      saveData: null,
      carType: {},
    };
  },
  async created() {
    this.loading = true;
    if (getAppId() == 'arcfox') {
      this.formList.find(x => x.fieldName == 'carType').itemList =this.createDictList('5543',[55431001])
    }else{
      this.formList.find(x => x.fieldName == 'carType').itemList =this.createDictList('5543')
    }
    await this.chuqi1();
    await this.chuqi();
    await this.getDetailFun(this.rowData.settleId);
    this.loading = false;
  },
  methods: {
    deleteFunkaohe(costItem) {
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          this.$notify({
            title: '提示信息',
            message: '删除成功',
            type: 'success',
          });
          this.$refs.table1.$refs.pageTable.EXECUTE_DELETE([costItem]);

          this.formList.map((x) => {
            if ('assessAmount' == x.fieldName) {
              x.initialValue = this.kaohesum - Number(costItem.assessAmount);
              this.kaohesum = this.kaohesum - Number(costItem.assessAmount);
              this.sumAmount();
            }
          });
        })
    },
    //删除索赔
    deleteFunsuopei(costItem) {
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          this.$notify({
            title: '提示信息',
            message: '删除成功',
            type: 'success',
          });
          this.$refs.table.$refs.pageTable.EXECUTE_DELETE([costItem]);

          this.formList.map((x) => {
            if ('claimAmount' == x.fieldName) {
              x.initialValue = Number(this.suopeisum - Number(costItem.finalSumAmount)).toFixed(2);
              this.suopeisum = Number(this.suopeisum - Number(costItem.finalSumAmount)).toFixed(2);
              this.sumAmount();
            }
          });
          if(!this.$refs.table.$refs.pageTable.list.length){
            this.formList.find((x) => x.fieldName === 'carType').disabled = false;
          }
        })
    },
    async chuqi1() {
      // const res = await getPartType({ type: 5546 });
      // if (res.resultCode == 200) {
      //   this.formList.find((x) => x.fieldName == 'settleStatus').initialValue = '';
      //   this.formList.find((x) => x.fieldName == 'settleStatus').itemList = res.data.map((y) => ({ text: y.codeCnDesc, value: y.codeId }));
      // }
    },
    async getDetailFun(val) {
      let res = await quyrPSettle(val);
      this.editRow = res.data;
      this.suopeisum = this.editRow.claimAmount;
      this.kaohesum = this.editRow.assessAmount;
      //为form赋值
      for (let i in res.data) {
        this.formList.map((x) => {
          if (x.fieldName == i) {
            x.initialValue = res.data[i];
          }
        });
      }
      //为table赋值(索赔单)
      if (200 == res.resultCode) {
        let data = res.data;
        if (isFormEmpty(data)) {
          data = {};
        }
        let records = data.claimList;
        if (isFormEmpty(records)) {
          records = [];
        }
        this.$refs.table.$refs.pageTable.EXECUTE_INSERT(records);
      }
      //为table赋值(考核单)
      if (200 == res.resultCode) {
        let data = res.data;
        if (isFormEmpty(data)) {
          data = {};
        }
        let records = data.assessList;
        if (isFormEmpty(records)) {
          records = [];
        }
        this.$refs.table1.$refs.pageTable.EXECUTE_INSERT(records);
      }
      if(this.$refs.table.$refs.pageTable.list.length){
        this.formList.find((x) => x.fieldName === 'carType').disabled = true;
      }
    },

    sumAmount() {
      let sum = 0;

      //索赔金额
      this.$refs.table.$refs.pageTable.list.map((x) => {
        sum += Number(x.finalSumAmount).toFixed(2);
      });
      //考核金额
      this.$refs.table1.$refs.pageTable.list.map((x) => {
        sum += Number(x.assessAmount).toFixed(2);
      });

      // this.$refs.peijianhuanshangjiantable.$refs.pageTable.list.map(x => {
      //   sum += Number(x.cmsClaimPrice);
      // });

      this.formList.map((x) => {
        if ('settleAmount' == x.fieldName) {
          x.initialValue = sum;
        }
      });
    },
    //索赔车辆属性
    async chuqi() {
      // const res = await getPartType({ type: 5543 });
      //
      // if(getAppId()=='arcfox'){
      //   delete res.data[0]
      //   this.formList.find((x) => x.fieldName == 'carType').initialValue = 55431002;
      // }
      // if (res.resultCode == 200) {
      //   this.formList.find((x) => x.fieldName == 'carType').itemList = res.data.map((y) => ({ text: y.codeCnDesc, value: y.codeId }));
      // }
    },
    formChangeHandle(val) {
      console.log(val);
      this.saveData = val;
    },
    //搜索获取数据
    changeHandle(val) {
      this.fetchParams = val;
      console.log(val);
    },
    //索赔单计算
    suopeidansave(val) {
      let list = this.$refs.table.$refs.pageTable.list;
      let values = [];
      val.map((v) => {
        if (!list.find((x) => x.claimId == v.claimId)) {
          values.push(v);
        }
      });
      this.$refs.table.$refs.pageTable.EXECUTE_INSERT(values);
      let suopeijine = 0;
      this.$refs.table.$refs.pageTable.list.map((x) => {
        suopeijine += Number(x.finalSumAmount);
      });
      this.formList.map((x) => {
        if ('claimAmount' == x.fieldName) {
          x.initialValue = Number(suopeijine);
        }
      });
      this.suopeisum = suopeijine;
      this.sumAmount();
      this.formList.find((x) => x.fieldName === 'carType').disabled = true;
      this.suopeidanFlag = false;
      // this.fetchParams = { ...this.fetchParams };
    }, //考核单计算
    kaohedansave(val) {
      let list = this.$refs.table1.$refs.pageTable.list;
      let values = [];
      val.map((v) => {
        if (!list.find((x) => x.assessId == v.assessId)) {
          values.push(v);
        }
      });
      this.$refs.table1.$refs.pageTable.EXECUTE_INSERT(values);

      let kaohejine = 0;
      this.$refs.table1.$refs.pageTable.list.map((x) => {
        kaohejine += Number(x.assessAmount);
      });
      this.formList.map((x) => {
        if ('assessAmount' == x.fieldName) {
          x.initialValue = Number(kaohejine);
        }
      });
      this.kaohesum = kaohejine;
      this.sumAmount();
      this.kaohedanFlag = false;
      this.fetchParams = { ...this.fetchParams };
    },
    suopeidanclose() {
      this.suopeidanFlag = false;
    },
    suopeidanadd() {
      this.formList.find((x) => x.fieldName === 'carType').rules = [{ required: true, message: '添加索赔单前，请选择车辆属性！', trigger: 'change' }];
      if (this.formList.find((x) => x.fieldName === 'carType').initialValue) {
        this.$refs.formPanel.SUBMIT_FORM();
        if(this.$refs.table.$refs.pageTable.list.length && this.$refs.table.$refs.pageTable.list[0].ifComm != this.saveData.carType){
          return this.$notify({
            title: '提示信息',
            message: '当前车辆属性,与索赔车辆属性不一致!',
            type: 'error'
          });
        }
        this.carType = this.saveData;
        this.suopeidanFlag = true;
      }
    },
    kaohedanclose() {
      this.kaohedanFlag = false;
    },
    kaohedanadd() {
      this.formList.find((x) => x.fieldName === 'carType').rules = [{ required: true, message: '添加考核单前，请选择车辆属性！', trigger: 'change' }];
      if (this.formList.find((x) => x.fieldName === 'carType').initialValue) {
        this.$refs.formPanel.SUBMIT_FORM();
        if(this.$refs.table.$refs.pageTable.list.length && this.$refs.table.$refs.pageTable.list[0].ifComm != this.saveData.carType){
          return this.$notify({
            title: '提示信息',
            message: '当前车辆属性,与索赔车辆属性不一致!',
            type: 'error'
          });
        }
        this.carType = this.saveData;
        console.log(56561);
        console.log(this.carType);
        this.kaohedanFlag = true;
      }

    },

    //选中
    selectChange(rows) {
      this.selectedRows = rows;
      console.log(this.selectedRows);
    },
    //保存
    async saveDialog() {
      this.$refs.formPanel.SUBMIT_FORM();

      let str = '';
      this.$refs.table.$refs.pageTable.list.map((x) => {
        str += x.claimId + ',';
      });
      this.saveData.claimIds = str;

      let str1 = '';
      this.$refs.table1.$refs.pageTable.list.map((x) => {
        str1 += x.assessId + ',';
      });
      this.saveData.assessIds = str1;

      console.log('进来了');
      console.log(this.saveData);

      // let arr = [];
      // this.$refs.table.$refs.pageTable.list.map(x => {
      //   arr.push(x);
      // });
      //
      // //附加项目
      // this.saveData.claimList = arr;

      for (let a in this.editRow) {
        if (this.saveData[a]) {
          this.editRow[a] = this.saveData[a];
        }
      }

      console.log('editRow');
      console.log(this.editRow);

      if (this.saveData.claimAmount === 0) {
        this.editRow.claimAmount = 0;
      }
      if (this.saveData.assessAmount === 0) {
        this.editRow.assessAmount = 0;
      }
      if (this.saveData.settleAmount === 0) {
        this.editRow.settleAmount = 0;
      }

      this.editRow.labourAmount = 0;
      this.editRow.partAmount = 0;
      this.editRow.addAmount = 0;
      this.$refs.table.$refs.pageTable.list.map((x) => {
        console.log(x.addAmount);
        this.editRow.labourAmount += Number(x.labourAmount);
        this.editRow.partAmount += Number(x.partAmount);
        this.editRow.addAmount += Number(x.addAmount);
      });

      if ((this.$refs.table.$refs.pageTable.list.length!==0)&&(this.formList.find((x) => x.fieldName === 'carType').initialValue)) {
        this.loading = true;
        let res = await editSave(this.editRow);
        if (res.resultCode === 200) {
          this.$emit('save');
          return this.$notify.success({ title: '提示信息', message: '保存成功' });
        } else {
          this.loading = false;
          // this.$notify.error({ title: '提示信息', message: res.errMsg || '保存失败!' });
          // this.closeDialog();
        }
        this.loading = false;
      } else {
        return this.$notify.error({title: '提示信息', message: '请检查索赔单列表或索赔车辆属性是否添加！'});
      }
    },
    //取消操作
    closeDialog() {
      this.$emit('close', { visible: false, data: this.selectedRows, type: 'close' });
    },
    chooseOrderNo() {
      this.visible = true;
    },
    add() {},
    createFormList() {
      return [
        {
          type: 'INPUT',
          label: '结算单号',
          fieldName: 'settleNo',
          disabled: true, // 只读
        },
        // {
        //   type: 'INPUT',
        //   label: '经销商代码',
        //   fieldName: 'ownerCode',
        //   disabled: true, // 只读
        // },
        // {
        //   type: 'INPUT',
        //   label: '经销商名称',
        //   fieldName: 'dealerName',
        //   disabled: true, // 只读
        // },
        {
          type: 'INPUT',
          label: '索赔金额',
          fieldName: 'claimAmount',
          disabled: true, // 只读
        },
        {
          type: 'INPUT',
          label: '考核金额',
          fieldName: 'assessAmount',
          disabled: true, // 只读
        },
        {
          type: 'INPUT',
          label: '结算金额',
          fieldName: 'settleAmount',
          disabled: true, // 只读
        },
        {
          type: 'SELECT',
          label: '结算单状态',
          fieldName: 'settleStatus',
          disabled: true, // 只读
          initialValue: '',
          itemList: this.createDictList('5546'),
        },
        {
          type: 'INPUT',
          label: '提交时间',
          fieldName: 'applyDate',
          disabled: true, // 只读
        },
        {
          type: 'SELECT',
          label: '索赔车辆属性',
          fieldName: 'carType',
          placeholder: '请选择',
          initialValue: '',
          rules: [{ required: true, message: '请选择车辆属性', trigger: 'blur' }],
          itemList: [],
        },
      ];
    },
    //索赔单列表
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: (props) => {
            return <span>{props.row.index + 1}</span>;
          },
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 100,
          fixed: 'left',
          render: (props) => {
            return (
              <div style="text-align:center">
                <multiuse-button size="mini" type="text" onClick={() => this.deleteFunsuopei(props.row)}>
                  删除
                </multiuse-button>
              </div>
            );
          },
        },
        { title: '索赔单号', dataIndex: 'claimNo', sorter: true },
        { title: '维修工单号', dataIndex: 'roNo', sorter: true },
        { title: 'VIN', dataIndex: 'vin', sorter: true },
        { title: '车型名称', dataIndex: 'modelName', sorter: true },
        { title: '索赔类型', dataIndex: 'cmsClaimTypeStr', sorter: true },
        { title: '索赔金额', dataIndex: 'finalSumAmount', sorter: true },
        { title: '工时费', dataIndex: 'labourFinalPrice', sorter: true },
        { title: '配件费', dataIndex: 'partrFinalPrice', sorter: true },
        { title: '附加费用', dataIndex: 'addFinalPrice', sorter: true },
        { title: '审核时间', dataIndex: 'checkAt', sorter: true },
        { title: '审核人', dataIndex: 'checkBy', sorter: true },
      ];
    },
    //考核单列表
    creatHeader1() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: (props) => {
            return <span>{props.row.index + 1}</span>;
          },
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 100,
          fixed: 'left',
          render: (props) => {
            return (
              <div style="text-align:center">
                <multiuse-button size="mini" type="text" onClick={() => this.deleteFunkaohe(props.row)}>
                  删除
                </multiuse-button>
              </div>
            );
          },
        },
        { title: '考核单号', dataIndex: 'assessNo', sorter: true },
        { title: '考核类型', dataIndex: 'assessTypeStr', sorter: true },
        { title: '考核金额', dataIndex: 'assessAmount', sorter: true },
        { title: '考核原因', dataIndex: 'assessReason', sorter: true },
        { title: '考核日期', dataIndex: 'assessDate', sorter: true, dateFormat: 'yyyy-MM-dd'},
        { title: '考核人', dataIndex: 'assessByStr', sorter: true },
      ];
    },
  },
};
</script>
<style lang="less" scoped></style>
